/***************************************************************
 *
 * Filename：TCPClient.cpp
 * Abstract：the design of TCP
 * version ：1.0
 *
 * Copyright (c) 2011 SCUT DT&P FY&XC
 *
***************************************************************/

#include "TCPClient.h"
#include <QFileDialog>

TCPClient::TCPClient(QHostAddress addr,QString fn,FileReveWindow *FRwin)
{
    TotalBytes = 0;
    bytesReceived = 0;
    fileNameSize = 0;
    fileName = fn;
    FileW = FRwin;
    localFile = new QFile(fn);
    UserAddr = addr;
    tcpClient = new QTcpSocket(this);
    newConnect();

    connect(tcpClient,SIGNAL(readyRead()),this,SLOT(readMessage()));
    connect(tcpClient,SIGNAL(error(QAbstractSocket::SocketError)),this,
            SLOT(displayError(QAbstractSocket::SocketError)));
}

//连接到服务器
void TCPClient::newConnect()
{
    blockSize = 0;
    tcpClient->abort();
    tcpClient->connectToHost(UserAddr,IPMSG_DEFAULT_PORT);
    qDebug()<<"to coonect the service in TCPClient::newConnect";
    time.start();
    qDebug()<<"start to settime";
    FileW->setlabeltext("try to connect TCPServer");
}

//执行接收,更新进度条
void TCPClient::readMessage()
{
    qDebug()<<"begin to reve file in TCPClient::readMessage";
    QDataStream in(tcpClient);
    in.setVersion(QDataStream::Qt_4_6);

    FileW->setlabeltext(QString("begin to reve file %1").arg(fileName));

    qDebug()<<"reve file structure information in TCPClient::readMessage";
    float useTime = time.elapsed();
    //如果接收到的数据小于16个字节，那么是刚开始接收数据，我们保存到//来的头文件信息
    if(bytesReceived <= sizeof(qint64)*2){
        if((tcpClient->bytesAvailable() >= sizeof(qint64)*2) && (fileNameSize == 0)){
            //接收数据总大小信息和文件名大小信息
            in>>TotalBytes>>fileNameSize;
            bytesReceived += sizeof(qint64)*2;
        }
        if((tcpClient->bytesAvailable() >= fileNameSize) && (fileNameSize != 0)){
            in>>fileName;
            //接收文件名，并建立文件
            bytesReceived +=fileNameSize;

            if(!localFile->open(QFile::WriteOnly)){
                //QMessageBox::warning(this,tr("应用程序"),tr("无法读取文件 %1:\n%2.").arg(fileName).arg(localFile->errorString()));
                return;
            }
        }else{
            return;
        }
    }
    qDebug()<<"reve real file information in TCPClient::readMessage";
    if(bytesReceived < TotalBytes){
        bytesReceived += tcpClient->bytesAvailable();
        inBlock = tcpClient->readAll();
        localFile->write(inBlock);
        inBlock.resize(0);
    }
    qDebug()<<bytesReceived<<"received"<<TotalBytes;
    //
    FileW->setProgressBar(TotalBytes,bytesReceived);
    double speed = bytesReceived / useTime;
    QString qtext = QString("reve %1MB (%2MB/s) \ntotal %3MB used time:%4s\n leave time:%5s")
                                       .arg(bytesReceived / (1024*1024))//已接收
                                       .arg(speed*1000/(1024*1024),0,'f',2)//速度
                                       .arg(TotalBytes / (1024 * 1024))//总大小
                                       .arg(useTime/1000,0,'f',0)//用时
                                       .arg(TotalBytes/speed/1000 - useTime/1000,0,'f',0);//剩余时间
    qDebug()<<"qtext:"<<qtext;
    FileW->setProgresstext(qtext);
    if(bytesReceived == TotalBytes)
    {
        tcpClient->close();
        FileW->setlabeltext("Finish to reve the file!!!!!!");
        qDebug()<<"finish to reve";
        localFile->close();   //接收完文件后，一定要关闭
    }
}

//错误处理
void TCPClient::displayError(QAbstractSocket::SocketError socketError)
{
    switch(socketError)
    {
        case QAbstractSocket::RemoteHostClosedError : break;
        default : qDebug() << tcpClient->errorString();
    }
}

